<?php
session_start();
include("config.php");
include("common/class/db.php");
include("service/saetv2.ex.class.php");

$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );

if (isset($_REQUEST['code'])) {

	$keys = array();
	$keys['code'] = $_REQUEST['code'];
	$keys['redirect_uri'] = WB_CALLBACK_URL;
	try {
		$token = $o->getAccessToken( 'code', $keys ) ;
	} catch (OAuthException $e) {

	}
}



if ($token) {
	$_SESSION['authorize'] = 1;
	$_SESSION['token'] = $token;
	setcookie( 'weibojs_'.$o->client_id, http_build_query($token) );
	$access_token = $_SESSION['token']['access_token'];
	$weiboUser = new SaeTClientV2(WB_AKEY,WB_SKEY,$_SESSION['token']['access_token']);
	$uid = $weiboUser->get_uid();
	$uid = $uid['uid'];
	$user  = DB::fetch_row("select * from `ntwt_user` where `uid`='{$uid}'");
	if(!$user){
		$wuser = $weiboUser->show_user_by_id($uid);
		$user = array();
		$user['uid']           = $wuser['id'];
		$user['weibo_name']    = $wuser['screen_name'];
		$user['url']           = "http://weibo.com/u/".$user['uid'];
		$user['avatar']        = $wuser['avatar_large'];
		$user['access_token']  = $access_token;
		$user['last_login_time'] = date('Y-m-d H:i:s');
		DB::insert("ntwt_user", $user);
	}else{
		$data = array();
		$data['access_token']    = $access_token;
		$data['last_login_time'] = date('Y-m-d H:i:s');
		$condition = array();
		$condition['uid'] = $uid;
	    DB::update("ntwt_user", $data, $condition);
	}
    header("Location:http://www.scnutn.com/demo/ntwt/");
}else{
	echo "fail";
}
?>
